package com.lenovo.agricultureServer.http.action;

import org.json.JSONException;
import org.json.JSONObject;

import com.lenovo.agricultureServer.R;
import com.lenovo.agricultureServer.db.DatabaseUtil;
import com.util.mail.MailSenderInfo;
import com.util.mail.SimpleMailSender;

import android.content.Context;
import android.util.Log;

public class FindPwdAction extends BaseAction 
{
	public static final String TAG = "findPassword";
	
	private Context context;
	public FindPwdAction(Context context)
	{
		this.context = context;
	}
	
	@Override
	protected String jasonPorcess(String param) 
	{
		JSONObject jsonResponse = new JSONObject();
		try 
		{
			JSONObject jsonRequest = new JSONObject(param);
			// 处理忘记密码请求
			String username = "";
			if(jsonRequest.has("username")){
				username = jsonRequest.getString("username");
			}
			String email = DatabaseUtil.queryUserEmail(username, context);
			String password = DatabaseUtil.queryUserPassword(username, context);
			if(email!=null && !email.equals("")){
				jsonResponse.put("result", "ok");
				jsonResponse.put("email", email);
				sendPasswordToEmail(username,email,password);
			} else {
				jsonResponse.put("result", "failed");
			}
			return  jsonResponse.toString();
		} 
		catch (JSONException e) 
		{
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	protected String soapPorcess(String param) {
		//TODO
		return "";
	}
	
	private void sendPasswordToEmail(String username, String email, String password)
	{
		if(username!=null && email!=null && password!=null)
		{
			String sentStr = "username : "+username+", password : "+password;
			Log.d(TAG,"send password to "+email+", content is ["+sentStr+"]");
			MailSenderInfo mailInfo = new MailSenderInfo();   
			mailInfo.setMailServerHost("smtp.163.com");   
			mailInfo.setMailServerPort("25");   
			mailInfo.setValidate(true);   
			mailInfo.setUserName("maoguo151@163.com");   
			mailInfo.setPassword("049074120");  
			mailInfo.setFromAddress("maoguo151@163.com");   
			mailInfo.setToAddress(email);   
			mailInfo.setSubject(context.getString(R.string.find_password_exp));   
			mailInfo.setContent(sentStr);   
			//这个类主要来发送邮件  
			SimpleMailSender sms = new SimpleMailSender();  
			sms.sendTextMail(mailInfo);//发送文体格式 
		}
	}

}
